package com.hanrui.android.activity.download;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hanrui.android.R;
import com.hanrui.android.adapter.DownAdapter;
import com.hanrui.android.library.base.ActionBarBaseActivity;
import com.hanrui.android.constant.Constant;
import com.hanrui.android.model.BaseFilesBean;
import com.hanrui.android.model.FilesBean;
import com.hanrui.android.net.Xutils;
import com.hanrui.android.utils.BaseUtils;
import com.hanrui.android.utils.DialogHelper;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 附件列表
 */
public class MyDownLoadActivity extends ActionBarBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    List<BaseFilesBean> dataList;

    DownAdapter adapter;

    String type;
    Bundle bundle;

    @Override
    protected void initInjector() {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_laod);

        unbinder = ButterKnife.bind(this);

        mTitleBar.setTitle("附件列表");

        initView();

    }


    private void initView() {

        bundle = getIntent().getExtras();

        type = bundle.getString("actType");


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DownAdapter();
        adapter.setEmptyView(getNoDataView(recyclerView));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                BaseFilesBean bean = (BaseFilesBean) adapter.getItem(position);

                if (bean.isDown()) {

                    BaseUtils.goFileOpne(MyDownLoadActivity.this,new File(Environment.getExternalStorageDirectory() + File.separator + "hanrui" + File.separator + dataList.get(position).getFileName()));

                }else {

                    down(bean,position);

                }

            }
        });


        PermissionUtils.permission(PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {

                        List<FilesBean> filesList = (List<FilesBean>) bundle.getSerializable("dataList");
                        getFiles(filesList);

                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                        LogUtils.d(permissionsDeniedForever, permissionsDenied);
                    }
                })
                .request();

    }

    private void getFiles(List<FilesBean> filesList) {

        if (null != filesList && filesList.size()>0){
            dataList = new ArrayList<>();
            for (FilesBean filesBean : filesList){
                BaseFilesBean bean;
                if (BaseUtils.fileIsExists(new File(Environment.getExternalStorageDirectory() + File.separator + "hanrui" + File.separator + filesBean.getFileName()))){
                    bean = new BaseFilesBean(filesBean.getId(),filesBean.getFileName(),filesBean.getFileExt(),true);
                }else {
                    bean = new BaseFilesBean(filesBean.getId(),filesBean.getFileName(),filesBean.getFileExt(),false);
                }
                dataList.add(bean);
            }
            adapter.setNewData(dataList);
        }

    }


    private void down(BaseFilesBean item, final int position){
        Xutils.getInstance().downLoadFile(Environment.getExternalStorageDirectory() + File.separator + "hanrui" + File.separator + item.getFileName(), Constant.downloadUrl+item.getId(), null, new Xutils.XDownLoadCallBack() {
            @Override
            public void onResponse(File result) {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onFinished() {
                ToastUtils.showShort("下载成功");
                adapter.getData().get(position).setDown(true);
                adapter.notifyItemChanged(position);
            }

            @Override
            public void onResponse(String result) {

            }
        });
    }


    public static void start(Context context,List<FilesBean> dataList){

        Intent intent = new Intent(context,MyDownLoadActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("dataList", (Serializable) dataList);
        intent.putExtras(bundle);
        context.startActivity(intent);


    }
}
